package com.itic.mall.system.orderjd.controller;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.itic.appbase.applications.exports.ExportExcel;
import com.itic.appbase.applications.exports.ExportExcelWithTemplet;
import com.itic.appbase.applications.sys.common.service.OutCommonService;
import com.itic.appbase.framework.common.constants.DBConst;
import com.itic.appbase.framework.common.constants.IticConst;
import com.itic.appbase.framework.common.constants.ResponseCode;
import com.itic.appbase.framework.common.controller.BaseController;
import com.itic.appbase.framework.exception.definition.ParameterErrorException;
import com.itic.appbase.framework.utils.CalendarHelper;
import com.itic.appbase.framework.utils.DateHelper;
import com.itic.appbase.framework.utils.StringHelper;
import com.itic.mall.system.orderjd.persistence.model.OrderJd;
import com.itic.mall.system.orderjd.persistence.model.OrderJdExample;
import com.itic.mall.system.orderjd.persistence.model.OrderJdExample.Criteria;
import com.itic.mall.system.orderjd.service.OrderJdService;
import com.itic.mall.system.orderjdproducts.persistence.dao.OrderJdProductsDao;
import com.itic.mall.system.orderjdproducts.persistence.model.OrderJdProducts;
import com.itic.mall.system.orderjdproducts.persistence.model.OrderJdProductsParamVo;



@Controller
@RequestMapping(value="/system/orderjd")
public class OrderJdController
     extends BaseController {
    @Autowired
    private OrderJdService orderJdService;
    @Autowired
	protected OutCommonService outCommonService;
    @Autowired
    private OrderJdProductsDao orderJdProductsDao ;
    
    //////////////////////////////////////////////////////常量区////////////////////////////////////////////////////////////////
    private static final String MODEL_NAME_CHINA = "京东订单";//中文名
    private static final String MODEL_NAME＿ENGLISH = "orderjd";//英文名
    private static final String PAGE_COMMON_PATH = "mall/system/orderjd/orderjd";//通用路径
    private static final String COMMON_URL = "/system/orderjd/";//通用路径
    
    //导出常量
    private static final String TEMP = "bzmc";//备注名称
    private static final String DATALIST = "dataList";//数据常量
    // 返回属性黑名单
    //private static String[] ignoreProperties = new String[] { "createUser", "isEffective", "createTime", "updateTime","orgCode" };


    //////////////////////////////////////////////////////页面跳转区////////////////////////////////////////////////////////////
   
    /*
     * 主页面
     */
    @RequestMapping(value="/init")
    public String init(Model model){
    	model.addAttribute("name_china", MODEL_NAME_CHINA);
    	model.addAttribute("name_english", MODEL_NAME＿ENGLISH);
    	model.addAttribute("common_url", COMMON_URL);
    	return PAGE_COMMON_PATH+"Main";
    }
    
    /*
     * 添加页面
     */
    @RequestMapping(value="/initAdd")
    public String initAdd(Model model){
    	model.addAttribute("name_china", MODEL_NAME_CHINA);
    	model.addAttribute("name_english", MODEL_NAME＿ENGLISH);
    	model.addAttribute("common_url", COMMON_URL);
    	return PAGE_COMMON_PATH+"Add";
    }
    
    /*
     * 编辑页面
     */
    @RequestMapping(value="/initEdit")
    public String initEdit(String id , Model model){
    	if( StringHelper.isNotBlank(id) ) {
    		OrderJd temp = orderJdService.get(id);
    		model.addAttribute("editData",iticJsonMapper.toJson(temp));
    		model.addAttribute("name_china", MODEL_NAME_CHINA);
        	model.addAttribute("name_english", MODEL_NAME＿ENGLISH);
        	model.addAttribute("common_url", COMMON_URL);
    	}else {
            throw new ParameterErrorException();
        }
    	return PAGE_COMMON_PATH+"Edit";
    }
    
    /*
     * 查看页面
     */
    @RequestMapping(value="/initView")
    public String initView(String id , Model model){
    	if( StringHelper.isNotBlank(id) ) {
    		
    		OrderJd temp  = orderJdService.get(id);
    		
    		model.addAttribute("viewEdit",iticJsonMapper.toJson(temp));
    		model.addAttribute("name_china", MODEL_NAME_CHINA);
        	model.addAttribute("name_english", MODEL_NAME＿ENGLISH);
        	model.addAttribute("common_url", COMMON_URL);
    	}else {
            throw new ParameterErrorException();
        }
    	
    	return PAGE_COMMON_PATH+"View";
    }
    
    /*
     * 导入页面
     */
    @RequestMapping(value="/initImp")
    public String initImp(Model model){
    	model.addAttribute("name_china", MODEL_NAME_CHINA);
    	model.addAttribute("name_english", MODEL_NAME＿ENGLISH);
    	model.addAttribute("common_url", COMMON_URL);
    	return PAGE_COMMON_PATH+"Imp";
    }
    
    
    //////////////////////////////////////////////////////业务代码区////////////////////////////////////////////////////////////
    
    
    
    /**
     * 添加模板管理数据
     * @param android
     * @return
     */
    @RequestMapping(value="/add")
    @ResponseBody
    public Map<String,String> add(OrderJd OrderJd){
    	
    	 Map<String, String> resultMap = new HashMap<String, String>();
         String result = ResponseCode.SERVER_ERROR.getCode();
         result = orderJdService.add(OrderJd);
         
         resultMap.put(IticConst.RESULT, result);
         return resultMap;
    }
    
    /**
     * 添加模板管理数据
     * @param android
     * @return
     */
    @RequestMapping(value="/nowsync")
    @ResponseBody
    public Map<String,String> nowsync(String id){
    	 Map<String, String> resultMap = new HashMap<String, String>();
    	 if( StringHelper.isNotBlank(id) ){
             OrderJd orderJd = orderJdService.get(id);
             if( null != orderJd ){
            	 resultMap = orderJdService.nowsync(orderJd);
             }
    	 }
         return resultMap;
    }
    
    
    /**
     * <p>Title:queryCondition </p>
     * <p>Description:封装查询条件 </p>
     * @param jzdw
     * @param jzdwExample
     * @return
     */
    private OrderJdExample queryCondition(HttpServletRequest request,OrderJd temp,String startTime,String endTime) {
    	
    	// 参数处理
        OrderJdExample example = new OrderJdExample();
        // 按创建时间倒序
        example.setOrderByClause("ORDER_DATE DESC");
        
        Criteria criteria = example.createCriteria().andIsEffectiveEqualTo( DBConst.TRUE );
      
        //过滤组织机构
        //User user = findUserSession(request);
        //criteria.andOrgCodeEqualTo(user.getOrganizationCode());
        
        // 查询条件
        if ( null != temp ) {
    	    //模糊查询
            if ( StringHelper.isNotBlank( temp.getOrderNum() ) ) {
                criteria.andOrderNumLike("%" + temp.getOrderNum() + "%");
            }
            //模糊查询
            if ( StringHelper.isNotBlank( temp.getTgwId() ) ) {
                criteria.andTgwIdLike("%" + temp.getTgwId() + "%");
            }
            //模糊查询
            if ( StringHelper.isNotBlank( temp.getTgwName() ) ) {
                criteria.andTgwNameLike("%" + temp.getTgwName() + "%");
            }
            //模糊查询
            if ( StringHelper.isNotBlank( temp.getIsJiesuan() ) ) {
                criteria.andIsJiesuanLike("%" + temp.getIsJiesuan() + "%");
            }
            //模糊查询
            if ( StringHelper.isNotBlank( temp.getIsJiesuan() ) ) {
                criteria.andIsJiesuanLike("%" + temp.getIsJiesuan() + "%");
            }
            if( StringHelper.isNotBlank(startTime) ){
            	criteria.andOrderDateGreaterThanOrEqualTo(DateHelper.getDateByStringDate(startTime+IticConst.START_TIME_SUFFIX));
            }
            if( StringHelper.isNotBlank(endTime) ){
            	criteria.andOrderDateLessThanOrEqualTo(DateHelper.getDateByStringDate(endTime+IticConst.END_TIME_SUFFIX));
            }
        }
        return example;
    }
    
   
    
    
    /**
     * 
     * @param goldType
     * @param request
     * @return
     */
    @RequestMapping(value = "/list")
    @ResponseBody
    public Map<String, Object> list(OrderJd OrderJd,String startTime,String endTime, HttpServletRequest request){
        // 声明返回对象
        Map<String, Object> resultMap = new HashMap<String, Object>();
        
        
        OrderJdExample example = this.queryCondition(request,OrderJd,startTime,endTime);
        // 封装分页参数
        example = this.handlePageQuery(request, example);
        
        
        // 获取信息总条数
        int total = orderJdService.count(example);
        
        // 获取数据
        List<OrderJd> list = orderJdService.list(example);
        
        // 数据返回处理
        resultMap.put(IticConst.TOTAL_RECORDS, total);
        resultMap.put(IticConst.DISPLAY_RECORDS, total);
        resultMap.put(IticConst.RESULT, ResponseCode.SUCCESS.getCode());
        resultMap.put(IticConst.DATA, list);
        return resultMap;

    }
    
    /**
     * 编辑保存
     * @param OrderJd
     * @return
     */
    @RequestMapping(value="/edit")
    @ResponseBody
    public Map<String,String> edit(String delFileIds , OrderJd OrderJd){
    
    	if( StringHelper.isNotBlank(delFileIds) ){
    		// 删除附件
    		outCommonService.deleteFiles(delFileIds);
    	}
    	
    	 Map<String, String> resultMap = new HashMap<String, String>();
         String result = ResponseCode.SERVER_ERROR.getCode();
         result = orderJdService.edit(OrderJd);
         
         resultMap.put(IticConst.RESULT, result);
         return resultMap;
    }
    
    

    /**
     * 删除
     * 
     */
    @RequestMapping(value = "/del")
    @ResponseBody
    public Map<String, String> del(String ids) {
        Map<String, String> resultMap = new HashMap<String, String>();
        String result = ResponseCode.SERVER_ERROR.getCode();

        //批量删除
        if (StringHelper.isNotBlank(ids)) {
        	
            List<String> idList = Arrays.asList(ids.split(","));
            
            OrderJdExample example = new OrderJdExample();
            example.createCriteria().andIdIn(idList);
          
            OrderJd OrderJd = new OrderJd();
            result = orderJdService.deleteByExample(OrderJd, example);
        } else {
            result = ResponseCode.PARAM_INVALID.getCode();
        }

        //删除一个
        /*
        if( StringHelper.isNotBlank(id) ){
            OrderJd OrderJd = new OrderJd();
            OrderJd.setId(id);
            result = orderJdService.delete(OrderJd);
        }
        */
        resultMap.put(IticConst.RESULT, result);
        return resultMap;
    }
    
    /**
     * 编辑保存
     * @param OrderJd
     * @return
     */
    @RequestMapping(value="/syncCurrent")
    @ResponseBody
    public Map<String,String> syncCurrent(){
    	 Map<String, String> resultMap = new HashMap<String, String>();
         String result = ResponseCode.SUCCESS.getCode();
         orderJdService.syncJdOrder();
         resultMap.put(IticConst.RESULT, result);
         return resultMap;
    }

    /**
     * 编辑保存
     * @param OrderJd
     * @return
     */
    @RequestMapping(value="/syncOne")
    @ResponseBody
    public Map<String,String> syncOne(String date){
    	 Map<String, String> resultMap = new HashMap<String, String>();
         String result = ResponseCode.SUCCESS.getCode();
         int hour=24;
   		 for( int i=hour;i>=0;i-- ){
   			orderJdService.subSyncJdOrder(date+i+"");
   		 }
         //orderJdService.syncJdOrderOneDay(date);
         resultMap.put(IticConst.RESULT, result);
         return resultMap;
    }
    
    /**
     * 同步某一天的某个小时
     * @param OrderJd
     * @return
     */
    @RequestMapping(value="/syncTime")
    @ResponseBody
    public Map<String,String> syncTime(String date){
    	 Map<String, String> resultMap = new HashMap<String, String>();
         String result = ResponseCode.SUCCESS.getCode();
         orderJdService.syncJdOrderOneDay(date);
         resultMap.put(IticConst.RESULT, result);
         return resultMap;
    }
    
    /**
     * 编辑保存
     * @param OrderJd
     * @return
     */
    @RequestMapping(value="/syncAll")
    @ResponseBody
    public Map<String,String> syncAll(){
    	 Map<String, String> resultMap = new HashMap<String, String>();
         String result = ResponseCode.SUCCESS.getCode();
         
         String initDate = "2017-11-22 23:59:59";//初始日期
 		 String nowDate = DateHelper.formatDateTime(new Date());
 		
     	 while (DateHelper.isGreater(nowDate, initDate)) {
     		//System.out.println(nowDate);
     		Date dateBefore = CalendarHelper.getDateBefore(DateHelper.getDateByStringDate(nowDate), 1);
     		nowDate = DateHelper.formatDateTime(dateBefore);
     		String forDate = DateHelper.getDateStringByDate(dateBefore, "yyyyMMdd");
     		orderJdService.syncJdOrderOneDay(forDate);
     	 }
         
         resultMap.put(IticConst.RESULT, result);
         return resultMap;
    }
    
    /**
     * 编辑保存
     * @param OrderJd
     * @return
     */
    @RequestMapping(value="/syncCurrentOver")
    @ResponseBody
    public Map<String,String> syncCurrentOver(){
    	 Map<String, String> resultMap = new HashMap<String, String>();
         String result = ResponseCode.SUCCESS.getCode();
         String dateStringByDate = DateHelper.getDateStringByDate(new Date(), "yyyyMMdd");
   		 int hour=24;
   		 for( int i=hour;i>=0;i-- ){
   			orderJdService.subSyncJdOrderOver(dateStringByDate+i+"");
   		 }
         resultMap.put(IticConst.RESULT, result);
         return resultMap;
    }

    /**
     * 编辑保存
     * @param OrderJd
     * @return
     */
    @RequestMapping(value="/syncOneOver")
    @ResponseBody
    public Map<String,String> syncOneOver(String date){
    	 Map<String, String> resultMap = new HashMap<String, String>();
         String result = ResponseCode.SUCCESS.getCode();
         //String dateStringByDate = DateHelper.getDateStringByDate(new Date(), "yyyyMMdd");
   		 int hour=24;
   		 for( int i=hour;i>=0;i-- ){
   			orderJdService.subSyncJdOrderOver(date+i+"");
   		 }
         resultMap.put(IticConst.RESULT, result);
         return resultMap;
    }
    
    /**
     * 同步某一天的某个小时
     * @param OrderJd
     * @return
     */
    @RequestMapping(value="/syncTimeOver")
    @ResponseBody
    public Map<String,String> syncTimeOver(String date){
    	 Map<String, String> resultMap = new HashMap<String, String>();
         String result = ResponseCode.SUCCESS.getCode();
         orderJdService.subSyncJdOrderOver(date);
         resultMap.put(IticConst.RESULT, result);
         return resultMap;
    }
    
    /**
     * 编辑保存
     * @param OrderJd
     * @return
     */
    @RequestMapping(value="/syncAllOver")
    @ResponseBody
    public Map<String,String> syncAllOver(){
    	 Map<String, String> resultMap = new HashMap<String, String>();
         String result = ResponseCode.SUCCESS.getCode();
         
         String initDate = "2017-11-27 23:59:59";//初始日期
 		 String nowDate = DateHelper.formatDateTime(new Date());
 		
     	 while (DateHelper.isGreater(nowDate, initDate)) {
     		//System.out.println(nowDate);
     		Date dateBefore = CalendarHelper.getDateBefore(DateHelper.getDateByStringDate(nowDate), 1);
     		nowDate = DateHelper.formatDateTime(dateBefore);
     		String forDate = DateHelper.getDateStringByDate(dateBefore, "yyyyMMdd");
     		orderJdService.syncJdOrderOneDayOver(forDate);
     	 }
         
         resultMap.put(IticConst.RESULT, result);
         return resultMap;
    }
    @RequestMapping(value = "/expOrder")
    @ResponseBody
    public void expOrder(HttpServletRequest request, HttpServletResponse response,OrderJd temp,String startTime,String endTime) {
    	try {
    		OrderJdExample example = new OrderJdExample();
    		example = this.queryCondition(request, temp, startTime,endTime);
    		List<OrderJd>  list = orderJdService.list(example);
    		/*List<com.itic.mall.system.orderjd.vo.OrderJdVo> orderJdVos = new ArrayList<>();
    		if(!list.isEmpty()) {
    			for(OrderJd order : list) {
    				com.itic.mall.system.orderjd.vo.OrderJdVo vo = new com.itic.mall.system.orderjd.vo.OrderJdVo();
    				vo.setCommisions(order.getCommisions());
    				vo.setJiesuanTime(order.getJiesuanTime());
    				vo.setOrderDate(order.getOrderDate());
    				vo.setOrderNum(order.getOrderNum());
    				vo.setOrderTotalMoney(order.getOrderTotalMoney());
    				vo.setTgwName(order.getTgwName());
    				vo.setYunUserNickName(order.getYunUserNickName());
    				OrderJdProductsParamVo paramVo = new OrderJdProductsParamVo();
    				paramVo.setOrderId(order.getId());
    				
    				List<OrderJdProducts> products =  this.orderJdProductsDao.selectOrderJdProductsNameByOrderId(paramVo);
    				if(!products.isEmpty()) 
    					vo.setProductName(products.get(0).getSkuName());
    				else
    					vo.setProductName("");
    				orderJdVos.add(vo);
    			}
    		}*/
    		//导出
    		Map<String, Object> exportMap = new HashMap<String, Object>();
    		exportMap.put(TEMP, MODEL_NAME＿ENGLISH);
    		exportMap.put(DATALIST, list);
    		ExportExcel exportExcel = new ExportExcelWithTemplet();
    		exportExcel.exportExcel(exportMap, request, response);
		} catch (Exception e) {
			 throw new RuntimeException("[TempletController | exp 模板示例导出异常]");
		}
    	
    	
    	
    }
}